package com.rupertjones.globalcron.config;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import static java.lang.String.format;

public class PropertyPlaceholder extends PropertyPlaceholderConfigurer {

    private static final Logger LOG = Logger.getLogger(PropertyPlaceholder.class);
    private volatile String propertiesLocation;

    public PropertyPlaceholder() {
        this.propertiesLocation = System.getenv("GLOBAL_CRON_HOME");
    }

    protected String resolvePlaceholder(String placeholder, Properties props) {
        Properties properties = getPropertiesFromHome();
        String property = getProperty(placeholder, properties);
        String displayValue = property;

        if (placeholder.contains("pass")) {
            displayValue = "******";
        }

        LOG.info(format("Loading property [%s] with value [%s].", placeholder, displayValue));
        return property;
    }

    private String getProperty(String key, Properties properties) {
        String property = properties.getProperty(key);
        if (property == null) {
            throw new RuntimeException(format("Couldn't find property [%s]. Returning an empty string.", key));
        }
        return property;
    }

    private Properties getPropertiesFromHome() {
        Properties properties = new Properties();
        String outsideConfiguration = format("%s/global-cron.properties", propertiesLocation);
        try {
            InputStream is = new FileInputStream(new File(outsideConfiguration));
            properties.load(is);
        } catch (FileNotFoundException fileNotFoundException) {
            LOG.error(format("Couldn't find properties file global-cron.properties at [%s]", propertiesLocation), fileNotFoundException);
            throw new RuntimeException(fileNotFoundException);
        } catch (IOException ioException) {
            LOG.error(ioException);
            throw new RuntimeException(ioException);
        }
        return properties;
    }
}
